//
//  UIImage+KYExtension.swift
//  KFManager
//
//  Created by kingly on 2016/11/15.
//  Copyright © 2016年 kingly inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. All rights reserved.
//

import UIKit

extension UIImage {

    /// 创建头像图像
    ///
    /// - parameter size:      尺寸
    /// - parameter backColor: 背景颜色
    ///
    /// - returns: 裁切后的图像
    func ky_clippingImage(size: CGSize?, backColor: UIColor = UIColor.white, lineColor: UIColor = UIColor.lightGray) -> UIImage? {

        var size = size
        if size == nil || size?.width == 0 {
            size = CGSize(width: 34, height: 34)
        }
        let rect = CGRect(origin: CGPoint(), size: size!)

        UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)

        backColor.setFill()
        UIRectFill(rect)

        let path = UIBezierPath(ovalIn: rect)
        path.addClip()

        draw(in: rect)

        let ovalPath = UIBezierPath(ovalIn: rect)
        ovalPath.lineWidth = 1
        lineColor.setStroke()
        ovalPath.stroke()

        let result = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return result
    }

    /// 生成指定大小的不透明图象
    ///
    /// - parameter size:      尺寸
    /// - parameter backColor: 背景颜色
    ///
    /// - returns: 图像
    func ky_makeImageWithSize(size: CGSize? = nil, backColor: UIColor = UIColor.white) -> UIImage? {

        var size = size
        if size == nil {
            size = self.size
        }
        let rect = CGRect(origin: CGPoint(), size: size!)

        UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)

        backColor.setFill()
        UIRectFill(rect)

        draw(in: rect)

        let result = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return result
    }

    /// 把颜色直接换换成图片
    ///
    /// - Parameter color: 颜色
    /// - Returns:  返回一个带颜色的图像
    func ky_creatImageWithColor(color:UIColor) -> UIImage?  {

        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)

        UIGraphicsBeginImageContext(rect.size)

        let creatImageContext = UIGraphicsGetCurrentContext()

        creatImageContext!.setFillColor(color.cgColor)

        creatImageContext!.fill(rect)

        let creatImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return creatImage
    }

    ///  改变一个图像的着色颜色,即更改image的TintColor
    ///
    /// - Parameter tintColor: 需要改变的着色颜色
    /// - Returns: 返回一个图像
    func ky_imageWithTintColor (tintColor: UIColor? = nil) -> UIImage?  {

        return  ky_imageWithTintColor(tintColor: tintColor, alpha: 1.0);
    }

    ///  改变一个图像的着色颜色,即更改image的TintColor
    ///
    /// - Parameter tintColor: 需要改变的着色颜色
    /// - Parameter alpha: alpha值  范围0～1 
    /// - Returns: 返回一个图像
    func ky_imageWithTintColor (tintColor: UIColor? = nil, alpha: CGFloat) -> UIImage?  {

        let rect = CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height)

        UIGraphicsBeginImageContextWithOptions(rect.size,false,self.scale)

        draw(in: rect)

        let ctx = UIGraphicsGetCurrentContext()

        ctx!.setFillColor((tintColor?.cgColor)!)

        ctx!.setAlpha(alpha)

        ctx?.setBlendMode(.sourceAtop)

        ctx!.fill(rect)

        let result = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return result;
    }
    

    
    /// 获得一个图片的镜像图片
    ///
    /// - Returns: 返回一个图片的镜像图片
    func ky_imageMirrored() -> UIImage {
        let width = self.size.width
        let height = self.size.height
        
        UIGraphicsBeginImageContext(self.size)
        let context = UIGraphicsGetCurrentContext()
        context!.interpolationQuality = .high
        
         let rect = CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height)
        
        context!.translateBy(x: width, y: height)
        context!.concatenate(CGAffineTransform(scaleX: -1, y: -1))
        context!.draw(self.cgImage!, in: rect)
      
        let imageRef = context!.makeImage()
        
        let resultImage = UIImage(cgImage: imageRef!)
        
        UIGraphicsEndImageContext()
        
        return resultImage
    }
    
    /// 设置图片的圆角（这种方式设置圆角比layer.cornerradius和layer.maskstobounds要好得多。）
    ///
    /// - Parameter cornerRadius: 圆角半径
    /// - Returns: 返回一个设置过圆角的图片
    func ky_imageWithCornerRadius(cornerRadius: CGFloat) -> UIImage {
        let frame = CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height)
        
        UIGraphicsBeginImageContext(self.size)
        
        // Add a clip before drawing anything, in the shape of an rounded rect
        UIBezierPath(roundedRect: frame, cornerRadius: cornerRadius).addClip()
        
        // Draw the image
        self.draw(in: frame)
        
        let imageWithCornerRadius = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return imageWithCornerRadius!
    }

    
    /// 设置UIImage到指定的大小。
    ///
    /// - Parameters:
    ///   - size: 指定大小
    ///   - withOriginalRatio: 是否UIImage应保持原比例 （YES 原比较 NO 指定的大小）
    /// - Returns: 返回指定的大小的UIImage
    func ky_imageScaledToSize(size: CGSize, withOriginalRatio: Bool) -> UIImage {
        var sizeFinal = size
        
        if withOriginalRatio {
            let ratioOriginal = self.size.width / self.size.height
            let ratioTemp = size.width / size.height
            
            if ratioOriginal < ratioTemp {
                sizeFinal.width = size.height * ratioOriginal
            } else if ratioOriginal > ratioTemp {
                sizeFinal.height = size.width / ratioOriginal
            }
        }

        UIGraphicsBeginImageContext(sizeFinal)
        self.draw(in: CGRect(x: 0.0, y: 0.0, width: sizeFinal.width, height: sizeFinal.height))
        let imageScaled: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return imageScaled
    }
    
    
    /// 指定的图片的旋转多少度
    ///
    /// - Parameter degrees: 旋转的度数
    /// - Returns: 返回一个旋转后的图片
    func ky_imageRotatedByDegrees(degrees: CGFloat) -> UIImage {
        let radians = CGFloat(Double.pi) * degrees / 180.0
        
        // calculate the size of the rotated view's containing box for our drawing space
        let rotatedViewBox = UIView(frame: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height))
        rotatedViewBox.transform = CGAffineTransform(rotationAngle: radians)
        
        let rotatedSize = rotatedViewBox.frame.size
        
        // Create bitmap context.
        UIGraphicsBeginImageContext(rotatedSize)
        let context = UIGraphicsGetCurrentContext()
        
        // Move the origin to the middle of the image so we will rotate and.
        context!.translateBy(x: rotatedSize.width / 2.0, y: rotatedSize.height / 2.0)
        
        // Rotate the image context
        context!.rotate(by: radians)
        
        // Now, draw the rotated/scaled image into the context
        context!.scaleBy(x: 1.0, y: -1.0)

        context!.draw(self.cgImage!, in: CGRect(x: -self.size.width / 2.0, y: -self.size.height / 2.0, width: self.size.width, height: self.size.height))
        
        let imageRotated = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return imageRotated!
    }
    



}

// MARK: - UIImageView with BlurEffect

public extension UIImageView {

    // initializer严格分为Designated Initializer和Convenience Initializer并且有语法定义。
    // 而在Objective-C中没有明确语法标记哪个初始化方式是convenience方法。
    // Swift中的convenience初始化方法, 只作为补充和提供使用上的方便. 
    // 所有的convenience方法都必须调用同一个类中的designated方法进行设置, 且不能被子类重写或从子类中以super的方式调用.
    // UIImageView(frame: self.view.frame, blurEffectStyle: .Light)
  public convenience init(frame: CGRect, blurEffectStyle: UIBlurEffect.Style) {
        self.init(frame: frame)
        
        let blurView = UIVisualEffectView(frame: self.bounds)
        self.addSubview(blurView)
        
        blurView.effect = UIBlurEffect(style: blurEffectStyle)
    }
    
}
